import { Inject, Provide } from "@midwayjs/core";
import { BaseService, CoolCommException } from "@cool-midway/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { In, Repository, Equal } from "typeorm";
import { OrderInfoEntity } from "../entity/info";
import { OrderItemEntity } from "../entity/item";
import { OrderAssignEntity } from "../entity/assign";
import { OrderLogisticsEntity } from "../entity/logistics";
import { OrderVerifyEntity } from "../entity/verify";
import { ProductInfoEntity } from "../../product/entity/info";
import { ProductItemEntity } from "../../product/entity/item";
import { ProviderProfileEntity } from "../../provider/entity/profile";
import { CapacityEntity } from "../../transport/entity/capacity";
import { Context } from "@midwayjs/koa";

/**
 * 订单详情聚合
 */
@Provide()
export class OrderAggregateService extends BaseService {
    @InjectEntityModel(OrderInfoEntity)
    orderInfoEntity: Repository<OrderInfoEntity>;

    @InjectEntityModel(OrderItemEntity)
    orderItemEntity: Repository<OrderItemEntity>;

    @InjectEntityModel(OrderAssignEntity)
    orderAssignEntity: Repository<OrderAssignEntity>;

    @InjectEntityModel(OrderLogisticsEntity)
    orderLogisticsEntity: Repository<OrderLogisticsEntity>;

    @InjectEntityModel(OrderVerifyEntity)
    orderVerifyEntity: Repository<OrderVerifyEntity>;

    @InjectEntityModel(ProviderProfileEntity)
    providerProfileEntity: Repository<ProviderProfileEntity>;

    @InjectEntityModel(CapacityEntity)
    capacityEntity: Repository<CapacityEntity>;

    @Inject()
    ctx: Context;

    /**
     * 重写 page 方法，只显示当前团队的订单
     */
    async page(query: any) {
        if (!this.ctx.provider?.id) {
            throw new CoolCommException('请先登录');
        }

        // 获取团队ID
        const teamId = await this.getTeamId(this.ctx.provider.id);
        if (!teamId) {
            // 如果没有团队，返回空结果
            return { list: [], pagination: { page: 1, size: 20, total: 0 } };
        }

        // 构建查询条件，限制只查询当前团队的订单
        const qb = this.orderInfoEntity
            .createQueryBuilder('a')
            .where('a.teamId = :teamId', { teamId })
            .orderBy('a.id', 'DESC');

        // 应用其他筛选条件
        if (query.status !== undefined) {
            qb.andWhere('a.status = :status', { status: query.status });
        }
        if (query.userId !== undefined) {
            qb.andWhere('a.userId = :userId', { userId: query.userId });
        }
        if (query.keyword) {
            qb.andWhere('a.orderNo LIKE :keyword', { keyword: `%${query.keyword}%` });
        }

        return this.entityRenderPage(qb, query);
    }

    /**
     * 重写 add 方法，自动关联团队ID
     */
    async add(param: any) {
        if (!this.ctx.provider?.id) {
            throw new CoolCommException('请先登录');
        }

        // 获取团队ID
        const teamId = await this.getTeamId(this.ctx.provider.id);
        if (!teamId) {
            throw new CoolCommException('请先加入团队或创建团队');
        }

        // 自动设置团队ID和服务人员录入者ID
        const orderData = {
            ...param,
            teamId,
            createdByProviderId: this.ctx.provider.id
        };

        return await super.add(orderData);
    }

    /**
     * 获取服务人员的团队ID
     */
    private async getTeamId(providerId: number): Promise<number | null> {
        const profile = await this.providerProfileEntity.findOne({
            where: { providerId: Equal(providerId) },
        });
        if (!profile) {
            return null;
        }
        if (profile.teamId) {
            return profile.teamId;
        }
        if (!profile.capacityId) {
            return null;
        }
        const capacity = await this.capacityEntity.findOne({
            where: { id: Equal(profile.capacityId) },
        });
        return capacity?.teamId ?? null;
    }

    /**
     * 聚合详情：主表、子项、当前有效分配、物流、核销状态
     */
    async detail(params: { orderId: number }) {
        const { orderId } = params || ({} as any);
        if (!orderId) throw new CoolCommException('缺少 orderId');

        // 主表
        const order = await this.orderInfoEntity.findOne({ where: { id: orderId } });
        if (!order) throw new CoolCommException('订单不存在');

        // 子项：联查产品与SKU名称
        const qb = this.orderItemEntity
            .createQueryBuilder('a')
            .leftJoin(ProductInfoEntity, 'b', 'a.productId = b.id')
            .leftJoin(ProductItemEntity, 'c', 'a.productItemId = c.id')
            .select([
                'a.*',
                'b.name as productName',
                'c.name as skuName',
            ])
            .where('a.orderId = :orderId', { orderId });
        const items = await qb.getRawMany();

        if (!items.length) {
            return { order, items: [] };
        }

        const itemIds = items.map(i => i.id).filter(Boolean);

        // 当前有效分配（status=1）
        const assigns = await this.orderAssignEntity.find({ where: { itemId: In(itemIds), status: 1 } });
        const itemIdToAssign = new Map<number, OrderAssignEntity>();
        assigns.forEach(a => !itemIdToAssign.has(a.itemId) && itemIdToAssign.set(a.itemId, a));

        // 物流信息（按 itemId）
        const logistics = await this.orderLogisticsEntity.find({ where: { itemId: In(itemIds) } });
        const itemIdToLogistics = new Map<number, OrderLogisticsEntity>();
        logistics.forEach(l => itemIdToLogistics.set(l.itemId, l));

        // 核销状态：存在 status=1 的核销记录则视为已核销
        const verifies = await this.orderVerifyEntity.find({ where: [{ orderId, status: 1 }, { itemId: In(itemIds), status: 1 }] as any });
        const orderVerified = verifies.some(v => !v.itemId);
        const verifiedItemIds = new Set<number>(verifies.filter(v => !!v.itemId).map(v => v.itemId));

        const mergedItems = items.map(raw => {
            const assign = itemIdToAssign.get(raw.id);
            const logistic = itemIdToLogistics.get(raw.id);
            const verify = orderVerified || verifiedItemIds.has(raw.id) ? 1 : 0;
            return {
                ...raw,
                assign,
                logistics: logistic || null,
                verifyStatus: verify,
            };
        });

        return {
            order,
            items: mergedItems,
            verifyStatus: orderVerified ? 1 : 0,
        };
    }
}


